<script setup>
import {onMounted, ref, watch} from "vue";
import local from "@/axios/local";
import moment from "moment";
import utils from "@/utils/storage";

const emits = defineEmits(['getData'])
const socket = ref(window.$io)
const props = defineProps(['tasks'])
const pendingUUidList = ref([])
const drawer = ref(false)
const taskList = ref([])


function showTask() {
  drawer.value = !drawer.value
}

function percentage(item) {
  return ((item.upload_chunk_files.length / item.totalChunks) * 100) + '%'
}

async function appendTask(item) {
  drawer.value = true
  await getData()
  taskList.value.push(item)
  pendingUUidList.value.push(item.uuid)
  let data = taskList.value[taskList.value.length - 1]
  for (let i = 1; i <= data.totalChunks; i++) {
    if (!item.upload_chunk_files.includes(i)) {
      data.index = i
      local.post('/cloud/uploadChunkIndex', item).then(res => {
        data.upload_chunk_files.push(i)
        taskList.value[taskList.value.length - 1] = data
      })
    }
  }

}

function time(row) {
  if (row.end_time && row.create_time) {
    // 获取结束时间
    const startTime = new Date(row.create_time); // 结束时间
    const endTime = new Date(row.end_time); // 结束时间
    // 计算毫秒差
    const timeDifference = endTime - startTime;

    const hours = Math.floor(timeDifference / (1000 * 60 * 60)); // 3600000 毫秒 = 1 小时

    const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)); // 60000 毫秒 = 1 分钟

    const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000); // 1000 毫秒 = 1 秒

    let str = ''
    str = hours > 0 ? hours + ' hour' : ''
    str = minutes > 0 ? minutes + ' min' : ''
    str = seconds > 0 ? seconds + ' s' : ''
    return str
  }
}

function startTask(arr) {
  for (let k of taskList.value) {
    if (arr.includes(k.uuid)) {
      if (k.type === 'upload') {
        socket.value.emit('ssh.uploadFileByFtp', k)
        socket.value.on(`uploadFileProgress_${k.uuid}`, r => {
          console.log(`uploadFileProgress_${k.uuid}`, '监听上传进度', r)
          k.progress = r.progress
        })
        socket.value.on(`uploadFileStatus_${k.uuid}`, r => {
          console.log(`uploadFileStatus_${k.uuid}`, '监听上传状态', r)
          k.status = r.status
          k.end_time = r.end_time
          emits('getData')
        })
        socket.value.on(`uploadFileSpeed_${k.uuid}`, r => {
          console.log(`uploadFileSpeed_${k.uuid}`, '监听上传速度', r)
          k.speed = r.speed
        })
      } else {
        socket.value.emit('ssh.downloadFiles', k)
        socket.value.on(`downloadFilesProgress_${k.uuid}`, r => {
          console.log(`downloadFilesProgress_${k.uuid}`, '监听下载进度', r)
          k.progress = r.progress
          k.download_size = r.download_size
          k.size = r.size
        })
        socket.value.on(`downloadFilesStatus_${k.uuid}`, r => {
          console.log(`downloadFilesStatus_${k.uuid}`, '监听下载状态', r)
          k.status = r.status
          k.end_time = r.end_time
          emits('getData')
        })
        socket.value.on(`downloadFilesSpeed_${k.uuid}`, r => {
          console.log(`downloadFilsSpeed_${k.uuid}`, '监听下载速度', r)
          k.speed = r.speed
        })
      }

    }

  }
}

function allReadySize(row) {
  if (!row.size) return '-'
  if (row.size && row.download_size) {
    return utils.renderSize(Number(row.download_size))
  }
  if (row.progress && row.size) {
    let num = (Number(row.progress) / 100) * Number(row.size)
    return utils.renderSize(num)
  } else {
    return 0
  }
}

watch(() => props.tasks, () => {
  let arr = []
  props.tasks.forEach(el => {
    let item = taskList.value.find(it => it.uuid === el.uuid)
    if (!item) {
      arr.push(el.uuid)
      taskList.value.push(JSON.parse(JSON.stringify(el)))
    }
  })
  taskList.value.sort((a, b) => a.create_time - b.create_time)
  console.log(arr)
  startTask(arr)
}, {deep: true, immediate: true})
defineExpose({
  showTask,
  appendTask
})
</script>

<template>
  <div>
    <div @click="showTask" class="task-icon">
      <img src="@/assets/task.png" alt="">
    </div>
    <el-drawer
        v-model="drawer"
        custom-class="my-drawer"
        append-to-body
        height="50%"
        title="任务列表"
        direction="btt"

    >
      <template #header>
        <h4 style="color:black;text-align: left">任务列表</h4>
      </template>
      <div class="table" style="height: 100%">
        <el-table height="100%" :data="taskList">
          <el-table-column width="100" show-overflow-tooltip align="center" label="类型" prop="type">
            <template #default="{row}">
              <el-tag v-if="row.type==='upload'" type="success" effect="plain">上传</el-tag>
              <el-tag v-if="row.type==='download'" type="primary" effect="plain">下载</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="150" show-overflow-tooltip align="center" label="名称" prop="name"/>
          <el-table-column width="150" show-overflow-tooltip align="center" label="大小" prop="size">
            <template #default="{row}">
              {{ allReadySize(row) }}{{ row.size ? '/' + utils.renderSize(row.size) : '' }}
            </template>
          </el-table-column>
          <el-table-column width="150" show-overflow-tooltip align="center" label="本地目录" prop="path"/>
          <el-table-column width="150" show-overflow-tooltip align="center" label="远程目录" prop="remote_path"/>
          <el-table-column width="120" show-overflow-tooltip align="center" label="上传速度" prop="speed"/>
          <el-table-column fixed="right" width="130" show-overflow-tooltip align="center" label="任务进度"
                           prop="progress">
            <template #default="{row}">
              <div style="justify-content: center;display: flex" class="flex">
                {{ Number(row.progress) }}%
              </div>
            </template>
          </el-table-column>
          <el-table-column width="200px" show-overflow-tooltip align="center" label="开始时间" prop="create_time">
            <template #default="{row}">
              {{ row.create_time ? moment(row.create_time).format('YYYY-MM-DD HH:mm:ss') : '' }}
            </template>
          </el-table-column>
          <el-table-column width="200px" show-overflow-tooltip align="center" label="结束时间" prop="end_time">
            <template #default="{row}">
              {{ row.end_time ? moment(row.end_time).format('YYYY-MM-DD HH:mm:ss') : '' }}
            </template>
          </el-table-column>
          <el-table-column width="200" show-overflow-tooltip align="center" label="总耗时" prop="time">
            <template #default="{row}">
              {{ time(row) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="100" show-overflow-tooltip align="center" label="状态" prop="time">
            <template #default="{row}">
              <div v-if="row.status===1">
                <el-tag type="success" effect="plain">{{ row.type === 'upload' ? '上传' : '下载' }}完成</el-tag>
              </div>
              <div v-if="row.status===0">
                <el-tag type="primary" effect="plain">{{ row.type === 'upload' ? '上传' : '下载' }}中</el-tag>
              </div>
              <div v-if="row.status===2">
                <el-tag type="danger" effect="plain">{{ row.type === 'upload' ? '上传' : '下载' }}失败</el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.task-icon {
  height: auto;
  position: fixed;
  bottom: 10%;
  right: 0;
  margin: 10px;
  z-index: 999;
  padding: 10px;
  box-sizing: border-box;
  cursor: pointer;

  img {
    width: 30px;
    height: auto;

  }
}

.flex {
  display: flex;
  align-items: center;
}
</style>
<style>
.el-drawer {
  height: 60% !important;
  display: flex;
  flex-direction: column;

}
</style>